package com.duapp.main;

import java.awt.BorderLayout;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

import chrriis.common.UIUtils;
import chrriis.dj.nativeswing.swtimpl.NativeInterface;
import chrriis.dj.nativeswing.swtimpl.components.JWebBrowser;

import com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel;

public class OnlinePlayer {
	private final static String TITLE_TUDOU = "土豆网：每个人都是生活的导演。";
	private final static String TITLE_YOUKU = "优酷网：世界都在看。";
	private static String url = null;
	private static Loading loading;

	public OnlinePlayer(String realUrl, String title) {
		JDialog dialog = new JDialog();
		dialog.setTitle(title);
		dialog.setBounds(30, 30, 608, 522);
		dialog.setResizable(false);
		JWebBrowser webBrowser = new JWebBrowser();
		webBrowser.setBarsVisible(false);
		webBrowser.setButtonBarVisible(false);
		webBrowser.setDefaultPopupMenuRegistered(false);
		webBrowser.navigate(realUrl);
		dialog.add(webBrowser, BorderLayout.CENTER);
		loading.dispose();
		dialog.setVisible(true);
		dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
	}

	public static void main(String[] args) {
		try {
			UIManager.setLookAndFeel(new WindowsClassicLookAndFeel());
			// UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
			// UIManager.setLookAndFeel(new MotifLookAndFeel());
			// UIManager.setLookAndFeel(new SynthLookAndFeel());
		} catch (Exception e) {
			e.printStackTrace();
		}
		boolean isOk = false;
		// http://v.youku.com/v_show/id_XNDM4OTI5NDg0.html
		while (!isOk) {
			url = JOptionPane.showInputDialog(null, "输入优酷或者土豆视频的地址");
			if (url == null) {
				return;
			}
			if (url == "" || url.length() == 0) {
				JOptionPane.showMessageDialog(null, "地址不能为空！", "错误",
						JOptionPane.ERROR_MESSAGE);
				continue;
			}
			if (url != null && url.indexOf(WriteToHtml.YOUKU) == -1
					&& url.indexOf(WriteToHtml.TUDOU) == -1) {
				JOptionPane.showMessageDialog(null, "必须是优酷或者土豆的地址！", "错误",
						JOptionPane.ERROR_MESSAGE);
				continue;
			}
			isOk = true;
		}

		loading = new Loading("images/loading.png");
		File directory = new File("");// 参数为空 设定为当前文件夹
		String courseFile = null;
		try {
			courseFile = directory.getCanonicalPath(); // 获取标准的路径
		} catch (IOException e) {
			e.printStackTrace();
		}
		final String realUrl = ("file:///" + courseFile + "/temp/temp.html");
		NativeInterface.open();
		UIUtils.setPreferredLookAndFeel();
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				String type = "";
				String id = "";
				if (url.indexOf(WriteToHtml.YOUKU) != -1) {
					id = url.substring(url.indexOf("id_") + 3,
							url.indexOf(".html"));
					type = WriteToHtml.YOUKU;
					new WriteToHtml().writeFile(type, id);
					new OnlinePlayer(realUrl, TITLE_YOUKU);
				} else {
					id = getIdOfTodou(url);
					type = WriteToHtml.TUDOU;
					new WriteToHtml().writeFile(type, id);
					new OnlinePlayer(realUrl, TITLE_TUDOU);
				}
			}

		});
		NativeInterface.runEventPump();

	}

	private static String getIdOfTodou(String urlStr) {
		// icode:"3n29ZRnSq2U"
		// http://www.tudou.com/programs/view/HsbfwE4_2rM/
		String[] strs = urlStr.split("/");
		try {
			String icode = "icode = '" + strs[strs.length - 1] + "'";
			URL url = new URL(urlStr); // 将urlstr字符串网址实例化为URL定位地址s
			URLConnection urlConn = url.openConnection(); // 打开网站链接s
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					urlConn.getInputStream(), "GBK")); // 实例化输入流，并获取网页代码
			String s; // 依次循环，直到读的值为空
			StringBuilder sb = new StringBuilder();
			while ((s = reader.readLine()) != null) {
				sb.append(s);
			}
			int icodeEnd = sb.indexOf(icode);
			String temp = null;
			int iidStart = 0, iidEnd = 0;
			if (icodeEnd == -1) {// 找不到符合的icode:""
				temp = sb.toString();
				iidStart = temp.indexOf("iid:") + 4;
				iidEnd = temp.indexOf(",", iidStart);
			} else {// 找得到
				temp = sb.substring(0, icodeEnd);
				iidStart = temp.lastIndexOf("iid = ") + 5;
				iidEnd = temp.indexOf(",", iidStart);
			}
			return temp.substring(iidStart, iidEnd).trim();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}
}
